#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>
#include <QDebug>
#include <QRadioButton>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    for(QRadioButton *bt:ui->groupBox->findChildren<QRadioButton*>()){
        connect(bt,&QRadioButton::clicked,this,&Widget::checkWho);
    }
    image = QImage(1920,1080,QImage::Format_ARGB32);
    image.fill(QColor(255,255,255,0));
}

Widget::~Widget()
{
    delete ui;
}

bool Widget::event(QEvent *event)
{
    QMouseEvent *e = static_cast<QMouseEvent*>(event);

    if(event->type()==QEvent::MouseButtonPress){
        first = last = e->pos();
        this->update();
    }
    else if(event->type()==QEvent::MouseMove){
        before = last;
        last = e->pos();
        painter.begin(&image);
        Widget::setPenStyle();
        switch (num) {
        case 1:
            path.clear();
            path.addRect(QRect(first,last).normalized());
            break;
        case 2:
            path.clear();
            path.addEllipse(QRect(first,last).normalized());
            break;
        case 3:
            path.clear();
            path = QPainterPath(first);
            path.lineTo(last);
            break;
        case 4:
            painter.drawLine(before,last);
            break;
        }
        painter.end();
        update();
    }
    else if(event->type()==QEvent::MouseButtonRelease){
        painter.begin(&image);
        Widget::setPenStyle();
        painter.drawPath(path);
        painter.end();
    }

    if(event->type()==QEvent::Paint){
        painter.begin(this);
        Widget::setPenStyle();
        painter.drawImage(0,0,image);
        if(!path.isEmpty())
            painter.drawPath(path);
        painter.end();
    }
    return QWidget::event(event);
}

void Widget::checkWho()
{
    this->num = ((QRadioButton*)QObject::sender())->whatsThis().toInt();
}

void Widget::setPenStyle()
{
    QPen pen(QColor(255,0,0));
    pen.setWidth(3);
    painter.setPen(pen);
    painter.setRenderHint(QPainter::Antialiasing, true);
}







